/*************************************************************************
	> File Name: tcp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/05 19:34
 ************************************************************************/

#pragma once

#include "Tools/threadPool.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cerrno>
#include "Task.hpp"

class TcpServer
{
public:
    TcpServer (uint16_t port, std::string ip = "0.0.0.0"):_port(port), _ip(ip), _tp_ptr(ThreadPool<Task>::getThreadPool())
    {}
    TcpServer()
    {}

    void initServer()
    {
        _tp_ptr->run();
        if ((_listensock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            logMessage(FATAL, "socket error, %d:%s", errno, strerror(errno));
            exit(1);
        }
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if (bind(_listensock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        if (listen(_listensock, gbacklog) < 0) {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "link success.");
    }

    void start()
    {
        int serversock;
        while (1) {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            serversock = accept(_listensock, (struct sockaddr*)&src, &len);
            if (serversock < 0) {
                logMessage(ERROR, "accept error, %d:%s", errno, strerror(errno));
                continue;
            }
            std::string cli_ip = inet_ntoa(src.sin_addr);
            uint16_t cli_port = ntohs(src.sin_port);
            logMessage(NORMAL, "accept success, from [%d]%s:%d", serversock, cli_ip.c_str(), cli_port);
            Task t(serversock, cli_port, cli_ip);
            _tp_ptr->pushTask(t);
        }
    }

    virtual ~TcpServer ()
    {
        close(_listensock);
    }

private:
    int _listensock;
    std::string _ip;
    uint16_t _port;
    ThreadPool<Task>* _tp_ptr;
    int gbacklog = 20;
};
